//
//  HZProuctCommentsViewController.m
//  app
//
//  Created by 刘华舟 on 15/6/3.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZProuctCommentsViewController.h"
#import "MJPhotoBrowser.h"
//model
#import "HZRemoteResult.h"
#import "HZProductCommentsVCData.h"
//view
#import "HZTableView.h"
#import "HZGoodsCommentCell.h"
#import "MyToast.h"
#import "HZOrderGoodsEmptyView.h"


//tools
#import "HZMallHttpManager.h"
#import "NSDictionary+SafetyGet.h"
#import "UIImageView+URL.h"

static const NSInteger kMallHomeLabelHeight = 60;

@interface HZProuctCommentsViewController()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UIButton *backBtn;

@property (strong, nonatomic) HZProductCommentsVCData *data;
@property (strong, nonatomic) HZRemoteResult *remoteData;


@property (strong, nonatomic) HZTableView *tableView;
@property (strong, nonatomic) HZOrderGoodsEmptyView *emptyView;

@end


@implementation HZProuctCommentsViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = HZ_WHITE_COLOR;
    
    self.title = @"商品评论";
    self.navigationController.navigationBar.hidden = NO;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //backBtn
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                            [self.ubo uw:kMallHomeLabelHeight uh:kMallHomeLabelHeight])];
    [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
    self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.backBtn addTarget:self action:@selector(backBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    

    
    

    
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf(CGPointMake(0, 0),
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT]) style:UITableViewStylePlain];
    self.tableView.backgroundColor = HZ_CLEAR_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.tableView.footerRefreshController = [[UIRefreshFooterController alloc] initWithTableView:self.tableView caller:[UBTargetCaller of:self action:@selector(loadMoreData)]];
    self.tableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.tableView viewController:self tryAgain:@selector(loadProductCommentsData)];
    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView.nothingRefreshView showLoadingMsg:nil errorMsg:@"加载失败，点击重试"];
    
    self.emptyView = [[HZOrderGoodsEmptyView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
    [self.emptyView hide];
    [self.view addSubview:self.emptyView];
    
    self.remoteData = [HZRemoteResult target:self action:@selector(finishedLoadGoodsSearchData:)];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = NO;

    
    if (([self.productID length]) && (self.data == nil)) {
        [self loadProductCommentsData];
    }
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

#pragma mark 加载数据
- (void)loadProductCommentsData{
    HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
    NSDictionary *params = @{APIKEY_mall_product_id:self.productID};
    [httpManager loadProductCommentsListWithParams:params result:self.remoteData];
}

#pragma mark 加载更多数据
- (void)loadMoreData{
    
    if (self.data.noMoreData) {
        [self.tableView endRefreshingAll];
        [MyToast showDefaultBottonWithText:@"已显示全部评论"];
    }else{
        HZGoodsCommentModel *model = [self.data.commentsArray lastObject];
        NSString *lastID = @"";
        if (model) {
            lastID = model.userID;
        }
        NSDictionary *params = @{APIKEY_mall_product_id:self.productID,
                                 APIKEY_mall_lastid:lastID};
        HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
        [httpManager loadMoreProductCommentsListWithParams:params result:self.remoteData];
    }
    
}

#pragma mark 完成加载数据
- (void)finishedLoadGoodsSearchData:(HZRemoteResult *)result{
    [self.tableView endRefreshingAll];
    
    if (result.response.status == JKResponseServerError || result.response.status == JKResponseLocalError) {
        [self.tableView.nothingRefreshView activeStop];
        [self.emptyView hide];
    }else if (result.response.status == JKResponseOK) {
        [self.tableView.nothingRefreshView remove];
        
        self.data = result.info;
        
        [self.emptyView hide];
        
        if (self.data) {
            
        }else{
            [self.tableView.nothingRefreshView remove];
            if(result.response.status == JKResponseTail){
                [self.emptyView showWithMessage:@"该商品暂无评论!"];
            }else{
                [self.emptyView showWithMessage:result.response.message];
            }
        }
        [self.tableView reloadData];
    }else{
        [self.tableView.nothingRefreshView remove];
        if(result.response.status == JKResponseTail){
            [self.emptyView showWithMessage:@"该商品暂无评论!"];
        }else{
            [self.emptyView showWithMessage:result.response.message];
        }
        
    }
}
#pragma mark 点击返回
- (void)backBtnOnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 点击查看大图
- (void)seeCommentsPics:(NSDictionary *)dict{
    MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
    NSMutableArray *photoArray = [NSMutableArray array];
    NSArray *pics = [dict arrayForKey:@"array"];
    NSString *picURL = [dict stringForKey:@"urlKey" nilValue:@""];
    NSInteger index = [dict integerForKey:@"index"];
    for (NSDictionary *pic in pics) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        //展位图
        UIImageView *photoPlaceHolder = [[UIImageView alloc] init];
        [photoPlaceHolder setImageWithURL:[pic stringForKey:picURL nilValue:@""]];
        photo.srcImageView = photoPlaceHolder;
        //原图
        photo.url = [NSURL URLWithString:[[pic stringForKey:picURL nilValue:@""] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        photo.save = NO;
        [photoArray addObject:photo];
    }
    photoBrowser.photos = [NSArray arrayWithArray:photoArray];
    
    if (index>=pics.count) {
        index = 0;
    }
    photoBrowser.currentPhotoIndex = index;
    [photoBrowser show];
}

#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.commentsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZGoodsCommentCell *cell = [HZGoodsCommentCell cellWithTableView:(HZTableView *)tableView];
    cell.picsTargetCaller = [UBTargetCaller of:self action:@selector(seeCommentsPics:)];
    cell.model = [self.data fetchCellModelAtRow:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZGoodsCommentModel *model = [self.data fetchCellModelAtRow:indexPath.row];
    return model.cellHeight;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

@end
